package com.campfire.intelligentsecurity.sys.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebFault;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebFilter(urlPatterns = {"/*"})
public class Sessionfilter implements Filter {

    private final Logger LOG = LoggerFactory.getLogger(getClass());
    private static final Set<String> AllowPath = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/login", "/logout","/pwd", "/register","/admin","/component","/config","/gis","/muiplayer","/api","/ws", "dataInterface","/face","/favicon.ico","/offlineVideo","/lunxun")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOG.info("filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean flag=false;
        Iterator<String> it=AllowPath.iterator();
        while (it.hasNext()){
            flag=path.contains(it.next());
            if (flag){
                break;
            }
        }
        if (!flag){
            String usercode = (String) request.getSession().getAttribute("usercode");
            if (Objects.isNull(usercode)) {
               /* response.sendRedirect(request.getContextPath()+"/login");*/
                PrintWriter out = response.getWriter();
                StringBuffer sb = new StringBuffer();
                sb.append("<html><script>window.open('"+request.getContextPath()+"/login','_top')</script></html>");
                response.setContentType("text/html; charset=UTF-8");
                out.write(sb.toString());
            }else{
                filterChain.doFilter(request, response);
            }
        }else{
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        LOG.info("filter destory");
    }
}
